package com.yumeko.api;

import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;

/**
 * @program: zookeeper
 * @description:
 * @author: Zheng Hao
 * @create: 2020-03-26 02:04
 */
public class GetNoteData implements Watcher {
    private static ZooKeeper zooKeeper;

    public static void main(String[] args) throws InterruptedException, IOException {
        zooKeeper = new ZooKeeper("192.168.106.128:2183", 10000, new GetNoteData());
        Thread.sleep(Integer.MAX_VALUE);
    }

    @Override
    public void process(WatchedEvent watchedEvent) {
        //当连接创建了，服务端发送给客户端SyncConnected事件
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            try {
                //调⽤获取单个节点数据⽅法
                getNoteData();
                getChildrens();
            } catch (KeeperException | UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        //⼦节点列表发⽣变化时，服务器会发出NodeChildrenChanged通知，但不会把变化情况告诉给客户端
        // 需要客户端⾃⾏获取，且通知是⼀次性的，需反复注册监听
        if (watchedEvent.getType() == Event.EventType.NodeChildrenChanged) {
            //再次获取节点数据
            try {
                List<String> children =
                        zooKeeper.getChildren(watchedEvent.getPath(), true);
                System.out.println(children);
            } catch (KeeperException e) {
                e.printStackTrace();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private static void getNoteData() throws KeeperException, InterruptedException, UnsupportedEncodingException {
        /**
         * path : 获取数据的路径
         * watch : 是否开启监听
         * stat : 节点状态信息
         * null: 表示获取最新版本的数据
         * zk.getData(path, watch, stat);
         */
        byte[] data = zooKeeper.getData("/yumekoCreate/y1", true,
                null);
        System.out.println(new String(data, "utf-8"));
    }

    private static void getChildrens() throws KeeperException,
            InterruptedException {
        /*
        path:路径
        watch:是否要启动监听，当⼦节点列表发⽣变化，会触发监听
        zooKeeper.getChildren(path, watch);
        */
        List<String> children = zooKeeper.getChildren("/yumekoCreate", true);
        System.out.println(children);
    }
}
